/*  
 *  @author Philip Stutz
 * 
 *  Copyright 2011 University of Zurich
 *      
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *         http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ch.uzh.ifi.ddis.ds2011.a3.helper;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.openrdf.rio.RDFHandler;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.RDFParser;
import org.openrdf.rio.ntriples.NTriplesParser;

/**
 * The class ParseHelper offers a simplified interface to the Sesame N-Triples
 * parser.
 */
public class ParseHelper {

	/**
	 * Parses the N-Triples file with the triple handler `handler`.
	 * 
	 * @param filePath
	 *            the file path
	 * @param handler
	 *            the parse handler
	 */
	public static void parseNTriplesFileWithHandler(String filePath,
			RDFHandler handler) {
		try {
			FileInputStream fileStream = new FileInputStream(filePath);
			parseNTriplesStreamWithHandler(fileStream, handler);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Parses the N-Triples web site at `uri` with the triple handle `handler`.
	 * 
	 * @param uri
	 *            the uri that contains N-Triples
	 * @param handler
	 *            the parse handler
	 */
	public static void parseNTriplesWebsiteWithHandler(String uri,
			RDFHandler handler) {
		try {
			InputStream websiteStream = new URL(uri).openStream();
			parseNTriplesStreamWithHandler(websiteStream, handler);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Parses the N-Triples stream `stream` with the triple handler `handler`.
	 * 
	 * @param stream
	 *            the N-Triples stream
	 * @param handler
	 *            the parse handler
	 */
	public static void parseNTriplesStreamWithHandler(InputStream stream,
			RDFHandler handler) {
		RDFParser parser = new NTriplesParser();
		parser.setRDFHandler(handler);
		try {
			parser.parse(stream, "");
		} catch (RDFParseException e) {
			e.printStackTrace();
		} catch (RDFHandlerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
